// database unit tool 

const defaultDb = 'website.db';
const database = process.env.defaultDb || defaultDb;
const sqlite = require('sqlite-async');

var getDbClientAsync = async (dbName)=>{
    dbName = dbName || database;
    let db = await sqlite.open(dbName);

    return db;
};

const object = {
    getDbClientAsync: async(dbName)=>{
        return await getDbClientAsync(dbName);
    },
    execSqlAsync : async (sql, ...argus)=>{
        let db = await getDbClientAsync();
            
        let count = await db.run(sql, ...argus);
        return count;
    },
    getRecordAsync : async (sql, ...argus) =>{
        let db = await getDbClientAsync();
        const record = await db.get(sql, ...argus);

        return record;
    },
    getAllAsync : async (sql, ...argus) =>{
        let db = await getDbClientAsync();
        const record = await db.all(sql, ...argus);

        return record;
    },
    /**
     * {list,total}
     */
    getPageListAsync: async(pageIndex, pageSize, selectSql, tableSql, whereSql, orderSql, ...argus)=>{
        let dataSql = `
            select ${selectSql}
            from ${tableSql}
            where 1=1 ${whereSql}
            ${orderSql && ("order by " + orderSql)}
            limit ${(pageIndex - 1) * pageSize},${parseInt(pageSize)}
        `;

        let list = await object.getAllAsync(dataSql, ...argus);

        let countSql = `
        select count(*) count
        from ${tableSql}
        where 1=1 ${whereSql}`;
        let total = await object.getRecordAsync(countSql, ...argus);

        return { list: list, total: total.count };
    }
};



module.exports = object;